package jaysun.core.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jaysun.core.action.Action;
import jaysun.core.action.ActionResult;
import jaysun.core.action.ResultContent;
import jaysun.core.action.ResultType;

@WebServlet("*.do")
public class FrontController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String DEFAULT_PACKAGE_NAME = "jaysun.business.action.";

	private static final String DEFAULT_ACTION_NAME = "";

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String contextPath = req.getContextPath() + "/";
		String servletPath = req.getServletPath();
		int start = 1;
		int end = servletPath.lastIndexOf(".do");
		String actionName = end > start ? servletPath.substring(start, end) + DEFAULT_ACTION_NAME : "";
		String actionClassName = DEFAULT_PACKAGE_NAME + actionName.substring(0, 1).toUpperCase()
				+ actionName.substring(1);
		
		System.out.println(actionName);
		System.out.println(actionClassName);

		try {
			Action action = (Action) Class.forName(actionClassName).newInstance();
			ActionResult actionResult = action.execute(req, resp);
			if (actionResult != null) {
				ResultContent resultContent = actionResult.getResultContent();
				ResultType resultType = actionResult.getResultType();
				switch (resultType) {
				case Redirect:
					resp.sendRedirect(contextPath + resultContent.getUrl());
					break;
				case Forward:
					req.getRequestDispatcher(resultContent.getUrl()).forward(req, resp);
					break;
				case Ajax:
					PrintWriter pw = resp.getWriter();
					pw.println(resultContent.getJson());
					pw.close();
					break;

				default:
				}
			}

		} catch (Exception e) {
		}

	}

}
